"use client"
import { useState, useEffect } from "react"
import { useSearchParams } from 'next/navigation'
import { Suspense } from 'react'
import { API_CONFIG } from "../../../../../url"

interface Order {
  orderId: number
  stuId: number
  orderNo: string
  transactionId: string | null
  payChannel: string | null
  paymentTime: string | null
  jiaocai: number
  application: number
  payment: number
  paymentStatus: number
  tonglianOrder: string | null
}

interface TaxInfo {
  id: string;
  stuId: string;
  sid: string;
  qdfphm: string;
  kplx: string;
  ykprq: string;
  ewmurl: string;
  // 其他可能的税务信息字段
}

interface ApiResponse {
  total: number
  list: Order[]
  pageNum: number
  pageSize: number
}

function OrderContent() {
  const searchParams = useSearchParams()
  const stuId = searchParams.get('stuId')
  console.log("stuId1111", stuId)
  const [order, setOrder] = useState<Order | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [token, setToken] = useState<string | null>(null)
  const [taxInfo, setTaxInfo] = useState<TaxInfo | null>(null)
  const [showTaxModal, setShowTaxModal] = useState(false)
  const [showNoTaxInfoModal, setShowNoTaxInfoModal] = useState(false)

  const [errorModal, setErrorModal] = useState({
    show: false,
    message: ''
  });

  useEffect(() => {
    setToken(localStorage.getItem('token'))
  }, [])

  const fetchOrder = async () => {
    try {
      setLoading(true)
      if (!stuId) throw new Error('缺少学生ID参数')
      if (!token) throw new Error('未找到用户token')

      const response = await fetch(
        `${API_CONFIG.BASE_URL}/api/pay/order?stuId=${stuId}`,
        {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`
          },
          credentials: 'include',
        }
      )

      if (!response.ok) throw new Error('获取订单失败')

      const data: ApiResponse = await response.json()
      setOrder(data.list[0] || null)
    } catch (err) {
      setError(err instanceof Error ? err.message : '未知错误')
    } finally {
      setLoading(false)
    }
  }

  // 新增：获取税务信息
  const fetchTaxInfo = async () => {
    try {
      if (!stuId || !token) return;

      const response = await fetch(`${API_CONFIG.BASE_URL}/api/tax/get`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({
          stuId: stuId,
          kplx: "0"
        }),
      });

      if (!response.ok) {
        // 如果接口返回错误，显示没有开票信息的提示
        setShowNoTaxInfoModal(true);
        return;
      }

      const data = await response.json();

      // 检查返回的数据是否有效
      if (!data || !data.qdfphm) {
        setShowNoTaxInfoModal(true);
        return;
      }

      setTaxInfo(data);
      setShowTaxModal(true);
    } catch (err) {
      setShowNoTaxInfoModal(true);
    }
  };
  const NoTaxInfoModal = () => (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div className="bg-white rounded-lg p-6 max-w-md w-full">
        <div className="flex justify-between items-center mb-4">
          <h3 className="text-xl font-semibold">提示</h3>
          <button
            onClick={() => setShowNoTaxInfoModal(false)}
            className="text-gray-500 hover:text-gray-700"
          >
            <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M6 18L18 6M6 6l12 12"></path>
            </svg>
          </button>
        </div>

        <div className="space-y-4">
          <p className="text-gray-700">当前订单没有开票信息</p>
          <div className="pt-2">
            <button
              onClick={() => setShowNoTaxInfoModal(false)}
              className="w-full py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
            >
              确定
            </button>
          </div>
        </div>
      </div>
    </div>
  );

  useEffect(() => {
    if (token && stuId) fetchOrder()
  }, [token, stuId])

  const getPaymentStatusText = (status: number) => {
    switch (status) {
      case 0: return '未支付'
      case 1: return '支付成功'
      case 2: return '支付失败'
      case 3: return '已退款'
      default: return '未知状态'
    }
  }
  const handleIssueRedInvoice = async () => {
    if (!taxInfo || !token) return;

    try {
      const confirmIssue = window.confirm('确定要开具红冲发票吗？此操作不可撤销。');
      if (!confirmIssue) return;

      const response = await fetch(
        `${API_CONFIG.BASE_URL}/api/redPunch?stuId=${stuId}`,
        {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`
          },
          body: JSON.stringify({
            fplxdm: "1",  // 发票类型代码
            chyydm: "2",
            yfphm: taxInfo.qdfphm,  // 原发票号码
            ykprq: taxInfo.ykprq   // 原开票日期
          }),
          credentials: 'include',
        }
      );

      if (!response.ok) throw new Error('开红冲发票失败');

      const result = await response.json();

      if (result.code === "00000") {
        // 检查ewmUrl是否有值
        if (result.data?.hzfpxx?.ewmUrl) {
          alert('红冲发票开具成功');
          fetchTaxInfo(); // 刷新税务信息
        } else {
          throw new Error('系统异常，请稍后再试');
        }
      } else {
        throw new Error(result.msg || '开红冲发票失败');
      }
    } catch (err) {
      setErrorModal({
        show: true,
        message: err instanceof Error ? err.message : '开红冲发票时发生错误'
      });
    }
  };


  // 新增：税务信息弹窗组件
  const TaxInfoModal = () => {
    if (!taxInfo) return null;

    return (
      <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
        <div className="bg-white rounded-lg p-6 w-full max-w-md mx-4">
          <div className="flex justify-between items-center mb-6">
            <h3 className="text-xl font-semibold text-gray-800">发票详细信息</h3>
            <button
              onClick={() => setShowTaxModal(false)}
              className="text-gray-400 hover:text-gray-600 transition-colors"
            >
              <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M6 18L18 6M6 6l12 12" />
              </svg>
            </button>
          </div>

          {/* 竖排三列数据展示 */}
          <div className="space-y-4 mb-6">
            {/* 发票号码行 */}
            <div className="flex flex-col sm:flex-row items-start sm:items-center gap-4">
              <div className="w-full sm:w-1/3">
                <span className="text-sm font-medium text-gray-500">发票号码</span>
              </div>
              <div className="w-full sm:w-2/3 bg-gray-50 p-3 rounded-lg">
                <div className="flex items-center justify-between">
                  <p className="text-base font-medium text-gray-800 break-all">
                    {taxInfo.qdfphm || <span className="text-gray-400">无</span>}
                  </p>
                  {taxInfo.qdfphm && (
                    <button
                      onClick={() => {
                        navigator.clipboard.writeText(taxInfo.qdfphm);
                        alert('发票号码已复制');
                      }}
                      className="ml-2 text-gray-400 hover:text-blue-500 transition-colors"
                      title="复制"
                    >
                      <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M8 5H6a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2v-1M8 5a2 2 0 002 2h2a2 2 0 002-2M8 5a2 2 0 012-2h2a2 2 0 012 2m0 0h2a2 2 0 012 2v3m2 4H10m0 0l3-3m-3 3l3 3" />
                      </svg>
                    </button>
                  )}
                </div>
              </div>
            </div>

            {/* 开票日期行 */}
            <div className="flex flex-col sm:flex-row items-start sm:items-center gap-4">
              <div className="w-full sm:w-1/3">
                <span className="text-sm font-medium text-gray-500">开票日期</span>
              </div>
              <div className="w-full sm:w-2/3 bg-gray-50 p-3 rounded-lg">
                <p className="text-base font-medium text-gray-800">
                  {taxInfo.ykprq ? (
                    <>
                      <span className="block">{new Date(taxInfo.ykprq).toLocaleDateString()}</span>
                      <span className="block text-sm text-gray-500">
                        {new Date(taxInfo.ykprq).toLocaleTimeString()}
                      </span>
                    </>
                  ) : (
                    <span className="text-gray-400">无</span>
                  )}
                </p>
              </div>
            </div>

            {/* 开票类型行 */}
            <div className="flex flex-col sm:flex-row items-start sm:items-center gap-4">
              <div className="w-full sm:w-1/3">
                <span className="text-sm font-medium text-gray-500">开票类型</span>
              </div>
              <div className="w-full sm:w-2/3 bg-gray-50 p-3 rounded-lg">
                <p className={`text-base font-medium ${taxInfo.kplx === '0' ? 'text-green-600' : 'text-red-600'
                  }`}>
                  {taxInfo.kplx === '0' ? '正数发票' : '负数发票'}
                </p>
              </div>
            </div>
          </div>

          {/* 操作按钮 - 垂直排列 */}
          <div className="space-y-3">
            {/* {taxInfo.ewmurl && (
              <button
                onClick={() => window.open(taxInfo.ewmurl, '_blank')}
                className="w-full flex items-center justify-center px-4 py-3 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors"
              >
                <svg className="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                </svg>
                查看电子发票
              </button>
            )} */}
            <button
              onClick={handleIssueRedInvoice}
              className="w-full flex items-center justify-center px-4 py-3 bg-red-600 hover:bg-red-700 text-white rounded-lg transition-colors"
            >
              <svg className="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
              </svg>
              开红冲发票
            </button>
          </div>
        </div>
      </div>
    );
  };

  if (loading) return (
    <div className="flex justify-center items-center h-64">
      <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-blue-500"></div>
    </div>
  )

  if (error) return (
    <div className="bg-red-50 border-l-4 border-red-500 p-4">
      <div className="flex">
        <div className="flex-shrink-0">
          <svg className="h-5 w-5 text-red-500" viewBox="0 0 20 20" fill="currentColor">
            <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
          </svg>
        </div>
        <div className="ml-3">
          <p className="text-sm text-red-700">{error}</p>
        </div>
      </div>
    </div>
  )

  //发票提示弹窗
  const ErrorModal = () => (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div className="bg-white rounded-lg p-6 max-w-md w-full">
        <div className="flex justify-between items-center mb-4">
          <h3 className="text-xl font-semibold">提示</h3>
          <button
            onClick={() => setErrorModal({ show: false, message: '' })}
            className="text-gray-500 hover:text-gray-700"
          >
            <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M6 18L18 6M6 6l12 12"></path>
            </svg>
          </button>
        </div>
        <div className="space-y-4">
          <p className="text-gray-700">{errorModal.message}</p>
          <div className="pt-2">
            <button
              onClick={() => setErrorModal({ show: false, message: '' })}
              className="w-full py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
            >
              确定
            </button>
          </div>
        </div>
      </div>
    </div>
  );

  return (
    <main className="min-h-screen bg-gray-50 py-8">
      <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="bg-white shadow rounded-lg overflow-hidden">
          {/* 标题区域 - 添加了返回按钮 */}
          <div className="px-6 py-5 border-b border-gray-200 bg-gray-50">
            <div className="flex items-center justify-between">
              <div className="flex items-center">
                <button
                  onClick={() => window.history.back()}
                  className="mr-3 p-1 rounded-md hover:bg-gray-200 transition-colors"
                  aria-label="返回上一页"
                >
                  <svg
                    xmlns="http://www.w3.org/2000/svg"
                    className="h-6 w-6 text-gray-600"
                    fill="none"
                    viewBox="0 0 24 24"
                    stroke="currentColor"
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth={2}
                      d="M10 19l-7-7m0 0l7-7m-7 7h18"
                    />
                  </svg>
                </button>
                <h2 className="text-xl font-semibold text-gray-800">订单详情</h2>
              </div>

              {/* 修改后的按钮组 - 使用flex布局并列展示 */}
              {order?.paymentStatus === 1 && (
                <div className="flex space-x-3">
                  <button
                    className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-colors"
                    onClick={fetchTaxInfo}
                  >
                    <svg className="-ml-1 mr-2 h-5 w-5" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
                      <path fillRule="evenodd" d="M4 4a2 2 0 00-2 2v4a2 2 0 002 2V6h10a2 2 0 00-2-2H4zm2 6a2 2 0 012-2h8a2 2 0 012 2v4a2 2 0 01-2 2H8a2 2 0 01-2-2v-4zm6 4a2 2 0 100-4 2 2 0 000 4z" clipRule="evenodd" />
                    </svg>
                    查看开票信息
                  </button>
                </div>
              )}
            </div>
          </div>

          {/* 订单详情内容 */}
          <div className="px-6 py-5">
            {order ? (
              <div className="space-y-6">
                {/* 基本信息卡片 */}
                <div className="bg-gray-50 p-4 rounded-lg">
                  <h3 className="text-lg font-medium text-gray-900 mb-4">基本信息</h3>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                      <p className="text-sm font-medium text-gray-500">订单编号</p>
                      <p className="mt-1 text-sm text-gray-900 font-mono">{order.orderNo}</p>
                    </div>
                    <div>
                      <p className="text-sm font-medium text-gray-500">支付状态</p>
                      <p className={`mt-1 text-sm font-medium ${order.paymentStatus === 1 ? 'text-green-600' : 'text-red-600'
                        }`}>
                        {getPaymentStatusText(order.paymentStatus)}
                      </p>
                    </div>
                    {order.paymentTime && (
                      <div>
                        <p className="text-sm font-medium text-gray-500">支付时间</p>
                        <p className="mt-1 text-sm text-gray-900">
                          {new Date(order.paymentTime).toLocaleString()}
                        </p>
                      </div>
                    )}
                    {order.payChannel && (
                      <div>
                        <p className="text-sm font-medium text-gray-500">支付渠道</p>
                        <p className="mt-1 text-sm text-gray-900">{order.payChannel}</p>
                      </div>
                    )}
                  </div>
                </div>

                {/* 费用信息卡片 */}
                <div className="bg-gray-50 p-4 rounded-lg">
                  <h3 className="text-lg font-medium text-gray-900 mb-4">费用明细</h3>
                  <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <div className="border-r border-gray-200 pr-4">
                      <p className="text-sm font-medium text-gray-500">教材费用</p>
                      <p className="mt-1 text-xl font-semibold text-gray-900">
                        ¥{order.jiaocai.toFixed(2)}
                      </p>
                    </div>
                    <div className="border-r border-gray-200 pr-4">
                      <p className="text-sm font-medium text-gray-500">报名费用</p>
                      <p className="mt-1 text-xl font-semibold text-gray-900">
                        ¥{order.application.toFixed(2)}
                      </p>
                    </div>
                    <div>
                      <p className="text-sm font-medium text-gray-500">总费用</p>
                      <p className="mt-1 text-2xl font-bold text-blue-600">
                        ¥{order.payment.toFixed(2)}
                      </p>
                    </div>
                  </div>
                </div>
              </div>
            ) : (
              <div className="text-center py-10">
                <svg
                  className="mx-auto h-12 w-12 text-gray-400"
                  fill="none"
                  viewBox="0 0 24 24"
                  stroke="currentColor"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={1}
                    d="M9.172 16.172a4 4 0 015.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
                  />
                </svg>
                <h3 className="mt-2 text-sm font-medium text-gray-900">未找到订单信息</h3>
                <p className="mt-1 text-sm text-gray-500">请检查订单编号是否正确</p>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* 税务信息弹窗 */}
      {showTaxModal && <TaxInfoModal />}

      {/* 无开票信息提示弹窗 */}
      {showNoTaxInfoModal && <NoTaxInfoModal />}
 
      {/* 开红冲发票提示弹窗 */}
      {errorModal.show && <ErrorModal />}
    </main>
  )
}

export default function OrderPage() {
  return (
    <Suspense fallback={
      <div className="flex justify-center items-center h-screen">
        <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-blue-500"></div>
      </div>
    }>
      <OrderContent />
    </Suspense>
  )
}